<?php
namespace App\Http\Controllers\Member;

use App\User;
use App\Models\UserScoreStream;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\Code;
/**
 *
 * @author Joker
 *        
 */
class AccountController extends MemberController
{
    
    public function __construct()
    {
        parent::__construct();
        
    }
    
    /**
     * 我的账户首页
     */
    public function index()
    {
        $currUser = User::find($this->uid);
        $creditLogs = $currUser->creditLog;
        $score = $currUser->score;
        return view('member.account.account')->with('logs',$creditLogs)->with('score',$score);
    }
    
    /**
     * 积分详情
     * @param integer $id
     */
    public function show($id)
    {
        $scoreStream = UserScoreStream::find($id);
        if(empty($scoreStream)) return $this->formatJson('error','没有更多数据');
        $scoreStream->is_read = 1;
        $scoreStream->save();
        $scoreStream->username = Auth::user()->name;
        
        return $this->formatJson('success','获取数据成功！',$scoreStream);
    }
    
    /**
     * 修改邮箱 
     */
    public function email()
    {
        return view('member.account.email');
    }
    
    /**
     * 修改密码
     */
    public function password()
    {
        return view('member.account.password');
    }
    
    /**
     * 修改基本资料
     */
    public function setting()
    {
        return view('member.account.setting');
    }
    
    public function check(Request $req)
    {
        $uname = $req->input('uname','');
        if(!empty($uname))
        {
            $hasuser = User::where('name','=',$uname)->where('id','<>',$this->uid)->first();
            if($hasuser)
            {
                return $this->formatJson('error','用户名已存在');
            }
            else
            {
                return $this->formatJson('success','用户名可用');
            }
        }
        $email = $req->input('email','');
        if(!empty($email))
        {
            $haseamil = User::where('email','=',$email)->where('id','<>',$this->uid)->first();
            if($haseamil)
            {
                return $this->formatJson('error','邮箱已存在');
            }
            else
            {
                return $this->formatJson('success','邮箱可用');
            }
        }
        $phone = $req->input('phone','');
        if(!empty($phone))
        {
            $hasphone = User::where('phone','=',$phone)->where('id','<>',$this->uid)->first();
            if($hasphone)
            {
                return $this->formatJson('error','手机号已存在');
            }
            else
            {
                return $this->formatJson('success','手机号可用');
            }
        }
    }
    
    /**
     *  用户邮箱修改、密码修改、账户基本资料修改
     * @param Request $req
     */
    public function store(Request $req) 
    {
        $data = $req->only('username','email','sex','phone','real_name','qq','signature','birth','password','oldpwd',
                'repassword','oldemail','email','types','verify_code');
        $curruser = User::find($this->uid);
        switch($data['types'])
        {
            case 'eamil':
                if(!empty($curruser->email))
                {
                    if(empty(trim($data['oldemail'])))
                    {
                        return redirect()->back()->withErrors(['error' => '原邮箱不能为空']);
                    }
                    elseif($curruser->email != trim($data['oldemail']))
                    {
                        return redirect()->back()->withErrors(['error' => '邮箱输入错误！']);
                    }
                }
                $emailExist = User::where('email','=',trim($data['username']))->first();
                if(!empty($emailExist))
                {
                    return redirect()->back()->withErrors(['error' => '邮箱已被使用！']);
                }
                if(!preg_match(config('app.email_rule'),$data['username'] ))
                {
                    return redirect()->back()->withErrors(['error' => '邮箱格式错误！']);
                }
                if(empty(trim($data['verify_code'])))
                {
                    return redirect()->back()->withErrors(['error' => '验证码不可为空！']);
                }
                if(empty(trim($data['password'])))
                {
                    return redirect()->back()->withErrors(['error' => '密码不能为空']);
                }
                elseif(password_verify($data['password'], $curruser->password) != 1)
                {
                    return redirect()->back()->withErrors(['error' => '原密码错误！']);
                }
                $nowtime = date('Y-m-d H:i:s');
                $isConti = Code::where('created_at','<',date('Y-m-d H:i:s',time()))
                ->where('created_at','>',date('Y-m-d H:i:s',strtotime("$nowtime - 10 minute")))
                ->where(['phone'=>$data['username'],'code'=>$data['verify_code'],'is_used'=>0,'type'=>2])->first();
                if (empty($isConti))
                {
                    return redirect()->back()->withErrors(['error'=> '邮箱验证码不正确']);
                }
                $isConti->update(['is_used'=>1]);
                $curruser->email = trim($data['username']);
                $curruser->save();
                return redirect('/member/setting');
                break;
            case 'pwd':
                if(empty(trim($data['oldpwd'])))
                {
                    return redirect()->back()->withErrors(['error' => '原始密码不能为空']);
                }
                elseif(password_verify($data['oldpwd'], $curruser->password) != 1) 
                {
                    return redirect()->back()->withErrors(['error' => '原密码错误！']);
                }
                if(empty(trim($data['password'])) || empty(trim($data['repassword'])))
                {
                    return redirect()->back()->withErrors(['error' => '新密码不能为空！']);
                }
                elseif(trim($data['password']) !== trim($data['repassword']))
                {
                    return redirect()->back()->withErrors(['error' => '两次输入的不一致！']);
                }
                if(empty(trim($data['username'])))
                {
                    return redirect()->back()->withErrors(['error' => '手机号或邮箱不能为空！']);
                }
                elseif(trim($data['username']) !== $curruser->phone && trim($data['username']) !== $curruser->email) 
                {
                    return redirect()->back()->withErrors(['error' => '手机号或邮箱不匹配！']);
                }
                elseif(empty(trim($data['verify_code'])))
                {
                    return redirect()->back()->withErrors(['error' => '验证码不可为空！']);
                }
                $response = password_check($data['password']);
                if($response  == 1)
                {
                    return redirect()->back()->withErrors(['error'=>'密码长度不可小于6个字符，且不可大于15个字符']);
                }
                elseif ($response == 2)
                {
                    return redirect()->back()->withErrors(['error'=>'密码不可为串数字']);
                }
                elseif($response == 3)
                {
                    return redirect()->back()->withErrors(['error'=>'密码过于简单，简易使用英文＋数字＋“!@#$%^&*()”']);
                }
                $nowtime = date('Y-m-d H:i:s');
                $isConti = Code::where('created_at','<',date('Y-m-d H:i:s',time()))
                            ->where('created_at','>',date('Y-m-d H:i:s',strtotime("$nowtime - 10 minute")))
                            ->where(['phone'=>$data['username'],'code'=>$data['verify_code'],'is_used'=>0,'type'=>2])->first();
                if (empty($isConti))
                {
                    return redirect()->back()->withErrors(['error'=> trans('passwords.phone_code')]);
                }
                $isConti->update(['is_used'=>1]);
                $curruser->password = bcrypt(trim($data['password']));
                $curruser->save();
                return redirect('member/setting');
                break;
            case 'info':
                $nameExits = User::where(['name'=>$data['username']])->where('id','<>',$this->uid)->first();
                if(!empty($nameExits))
                {
                    return redirect()->back()->withErrors(['name'=>'用户名已存在！']);
                }
                if(trim($data['username']))
                    $curruser->name = trim($data['username']);
                
                $curruser->sex = intval($data['sex']);
                if(trim($data['real_name']))
                    $curruser->real_name = trim($data['real_name']);
                if(trim($data['qq']))
                    $curruser->qq = intval($data['qq']);
                if(trim($data['signature']))
                    $curruser->signature = trim($data['signature']);
                if(trim($data['birth']))
                {
                    $birth = explode("-", $data['birth']);
                    $curruser->birth_year = $birth[0];
                    $curruser->birth_month = $birth[1];
                }
                $curruser->save();
                return redirect('/member/setting');
                break;
        }
        
    }
}